package com.CRApp.service.impl;

import com.CRApp.mapper.ArticleMapper;
import com.CRApp.pojo.Article;
import com.CRApp.pojo.ArticleHistory;
import com.CRApp.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    
    @Autowired
    private ArticleMapper articleMapper;
    
    @Override
    public List<Article> getEssayList() {
        return articleMapper.getEssayList();
    }
    
    @Override
    public List<Article> search(String keyword) {
        return articleMapper.search(keyword);
    }

    @Override
    public Article getEssayById(Integer id) {
        return articleMapper.getEssayId(id);
    }

    @Override
    public List<Article> getUserCollections(Integer userId) {
        return articleMapper.getUserCollections(userId);
    }

    @Override
    public boolean toggleCollection(Integer userId, Integer articleId) {
        // 检查是否已收藏
        boolean isCollected = isCollected(userId, articleId);
        if (isCollected) {
            // 已收藏则取消收藏
            articleMapper.removeCollection(userId, articleId);
            return false;
        } else {
            // 未收藏则添加收藏
            articleMapper.addCollection(userId, articleId);
            return true;
        }
    }

    @Override
    public boolean isCollected(Integer userId, Integer articleId) {
        return articleMapper.checkCollection(userId, articleId) > 0;
    }

    @Override
    public List<ArticleHistory> getUserHistory(Integer userId) {
        return articleMapper.getUserHistory(userId);
    }

    @Override
    public void clearHistory(Integer userId) {
        articleMapper.clearHistory(userId);
    }

    @Override
    public void addHistory(Integer userId, Integer articleId) {
        // 检查今天是否已有浏览记录
        Integer historyId = articleMapper.checkTodayHistory(userId, articleId);
        
        if (historyId != null) {
            // 如果今天已有记录，更新访问时间
            articleMapper.updateAccessTime(historyId);
        } else {
            // 如果今天没有记录，插入新记录
            articleMapper.insertHistory(userId, articleId);
        }
    }
} 